package cn.iocoder.yudao.module.reading.controller.admin.ai;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.reading.controller.admin.ai.vo.AdminAiProcessReqVO;
import cn.iocoder.yudao.module.reading.controller.admin.ai.vo.AdminAiProcessRespVO;
import cn.iocoder.yudao.module.reading.service.ai.AiService;
import cn.iocoder.yudao.module.reading.util.AiServiceTestUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 管理后台 - AI 服务
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - AI 服务")
@RestController
@RequestMapping("/reading/admin/ai")
@Validated
@Slf4j
public class AdminAiController {

    @Resource
    private AiService aiService;

    @Value("${reading.ai.openrouter.api-key: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}")
    private String apiKey;

    @Value("${reading.ai.openrouter.base-url:https://openrouter.ai/api/v1}")
    private String baseUrl;

    @Value("${reading.ai.openrouter.model:openrouter/horizon-beta}")
    private String model;

    @PostMapping("/process")
    @Operation(summary = "AI文本处理（润色/翻译）")
    @PreAuthenticated
    public CommonResult<AdminAiProcessRespVO> processText(@Valid @RequestBody AdminAiProcessReqVO reqVO) {
        log.info("管理后台AI文本处理请求: operation={}, sourceLanguage={}, targetLanguage={}", 
                reqVO.getOperation(), reqVO.getSourceLanguage(), reqVO.getTargetLanguage());
        
        String processedContent;
        if ("translate".equals(reqVO.getOperation())) {
            processedContent = aiService.translateText(reqVO.getContent(), reqVO.getSourceLanguage(), reqVO.getTargetLanguage());
        } else {
            processedContent = aiService.polishText(reqVO.getContent());
        }
        
        return success(new AdminAiProcessRespVO().setContent(processedContent));
    }

    @GetMapping("/test")
    @Operation(summary = "测试AI服务连接")
    @PreAuthenticated
    public CommonResult<Map<String, Object>> testAiService() {
        log.info("开始测试AI服务连接...");

        Map<String, Object> result = new HashMap<>();
        result.put("apiKey", apiKey.substring(0, Math.min(10, apiKey.length())) + "***");
        result.put("baseUrl", baseUrl);
        result.put("model", model);

        try {
            boolean success = AiServiceTestUtil.testOpenRouterConnection(apiKey, baseUrl, model);
            result.put("success", success);
            result.put("message", success ? "AI服务连接测试成功" : "AI服务连接测试失败");

            if (success) {
                log.info("✅ AI服务连接测试成功");
            } else {
                log.error("❌ AI服务连接测试失败");
            }

        } catch (Exception e) {
            log.error("AI服务连接测试异常", e);
            result.put("success", false);
            result.put("message", "AI服务连接测试异常: " + e.getMessage());
        }

        return success(result);
    }

    @GetMapping("/models")
    @Operation(summary = "获取可用的免费模型列表")
    @PreAuthenticated
    public CommonResult<Map<String, Object>> getAvailableModels() {
        Map<String, Object> result = new HashMap<>();
        result.put("currentModel", model);
        result.put("availableModels", AiServiceTestUtil.getAvailableFreeModels());
        result.put("message", "建议在配置文件中尝试不同的模型，如果当前模型不可用");

        return success(result);
    }

}
